import 'package:bot_toast/bot_toast.dart';
import 'package:dio/dio.dart';
import 'package:get/get.dart';
import 'base_service.dart';
import '../utils/rsa_utils.dart';

/// API服务类 - GetX服务
class ApiService extends GetxService {
  final BaseService _baseService = BaseService();

  /// 用户登录
  Future<Map<String, dynamic>?> login({
    required String phone,
    required String password,
  }) async {
    try {
      // RSA加密手机号和密码
      final encryptedPhone = RSAUtils.encryptPhone(phone);
      final encryptedPassword = RSAUtils.encryptPassword(password);

      final response = await _baseService.post<Map<String, dynamic>>(
        '/user/login',
        data: {'phone': encryptedPhone, 'password': encryptedPassword},
      );

      if (response.data != null) {
        final data = response.data!;
        if (data['code'] == 0 && data['success'] == true) {
          return data;
        } else {
          BotToast.showText(text: data['msg'] ?? '登录失败');
          return null;
        }
      } else {
        throw Exception('登录响应数据为空');
      }
    } on DioException catch (e) {
      print('登录网络错误: ${e.message}');
      throw Exception('网络环境不佳，请稍后尝试');
    } catch (e) {
      print('登录错误: $e');
      throw Exception('网络环境不佳，请稍后尝试');
    }
  }

  /// 获取用户信息
  Future<Map<String, dynamic>> getUserInfo() async {
    try {
      final response = await _baseService.get<Map<String, dynamic>>(
        '/user/getUserInfo',
      );

      if (response.data != null) {
        final data = response.data!;
        if (data['code'] == 0 && data['success'] == true) {
          return data;
        } else {
          throw Exception(data['msg'] ?? '获取用户信息失败');
        }
      } else {
        throw Exception('获取用户信息响应数据为空');
      }
    } on DioException catch (e) {
      print('获取用户信息网络错误: ${e.message}');
      throw Exception('网络环境不佳，请稍后尝试');
    } catch (e) {
      print('获取用户信息错误: $e');
      throw Exception('网络环境不佳，请稍后尝试');
    }
  }

  /// 退出登录
  Future<Map<String, dynamic>> logout() async {
    try {
      final response = await _baseService.get<Map<String, dynamic>>(
        '/user/loginOut',
      );

      if (response.data != null) {
        final data = response.data!;
        if (data['code'] == 0 && data['success'] == true) {
          // 清除认证信息
          _baseService.clearAuth();
          return data;
        } else {
          throw Exception(data['msg'] ?? '退出登录失败');
        }
      } else {
        throw Exception('退出登录响应数据为空');
      }
    } on DioException catch (e) {
      print('退出登录网络错误: ${e.message}');
      throw Exception('网络环境不佳，请稍后尝试');
    } catch (e) {
      print('退出登录错误: $e');
      throw Exception('网络环境不佳，请稍后尝试');
    }
  }

  /// 获取系统配置（用户协议和隐私政策链接）- 无需认证
  Future<Map<String, dynamic>> getSysConfig() async {
    try {
      final response = await _baseService.get<Map<String, dynamic>>(
        '/user/getSysConfig',
      );

      if (response.data != null) {
        final data = response.data!;
        if (data['code'] == 0 && data['success'] == true) {
          return data;
        } else {
          throw Exception(data['msg'] ?? '获取系统配置失败');
        }
      } else {
        throw Exception('获取系统配置响应数据为空');
      }
    } on DioException catch (e) {
      print('获取系统配置网络错误: ${e.message}');
      throw Exception('网络环境不佳，请稍后尝试');
    } catch (e) {
      print('获取系统配置错误: $e');
      throw Exception('网络环境不佳，请稍后尝试');
    }
  }

  /// 获取Banner信息
  Future<Map<String, dynamic>> getBannerInfos() async {
    try {
      final response = await _baseService.get<Map<String, dynamic>>(
        '/banner/getInfos',
      );

      if (response.data != null) {
        final data = response.data!;
        if (data['code'] == 0 && data['success'] == true) {
          return data;
        } else {
          throw Exception(data['msg'] ?? '获取Banner信息失败');
        }
      } else {
        throw Exception('获取Banner信息响应数据为空');
      }
    } on DioException catch (e) {
      print('获取Banner信息网络错误: ${e.message}');
      throw Exception('网络环境不佳，请稍后尝试');
    } catch (e) {
      print('获取Banner信息错误: $e');
      throw Exception('网络环境不佳，请稍后尝试');
    }
  }

  /// 获取广告弹窗信息
  Future<Map<String, dynamic>> getAdvertisementInfos() async {
    try {
      final response = await _baseService.get<Map<String, dynamic>>(
        '/advertisement/getInfos',
      );

      if (response.data != null) {
        final data = response.data!;
        if (data['code'] == 0 && data['success'] == true) {
          return data;
        } else {
          throw Exception(data['msg'] ?? '获取广告弹窗信息失败');
        }
      } else {
        throw Exception('获取广告弹窗信息响应数据为空');
      }
    } on DioException catch (e) {
      print('获取广告弹窗信息网络错误: ${e.message}');
      throw Exception('网络环境不佳，请稍后尝试');
    } catch (e) {
      print('获取广告弹窗信息错误: $e');
      throw Exception('网络环境不佳，请稍后尝试');
    }
  }

  /// 获取云存订单列表
  Future<Map<String, dynamic>> getCloudStorageOrders({
    String? channelName,
    String? customerName,
    int? cloudStorageType,
    int? cloudStorageDurationMin,
    int? cloudStorageDurationMax,
    int? cloudStorageStream,
    int pageNo = 1,
    int pageSize = 10,
    String? deviceId,
    String? channelId,
    String? createdAtStart,
    String? createdAtEnd,
    int? status,
  }) async {
    try {
      final data = <String, dynamic>{'pageNo': pageNo, 'pageSize': pageSize};

      // 添加可选参数
      if (channelName != null) data['channelName'] = channelName;
      if (customerName != null) data['customerName'] = customerName;
      if (cloudStorageType != null) data['cloudStorageType'] = cloudStorageType;
      if (cloudStorageDurationMin != null)
        data['cloudStorageDurationMin'] = cloudStorageDurationMin;
      if (cloudStorageDurationMax != null)
        data['cloudStorageDurationMax'] = cloudStorageDurationMax;
      if (cloudStorageStream != null)
        data['cloudStorageStream'] = cloudStorageStream;
      if (deviceId != null) data['deviceId'] = deviceId;
      if (channelId != null) data['channelId'] = channelId;
      if (createdAtStart != null) data['createdAtStart'] = createdAtStart;
      if (createdAtEnd != null) data['createdAtEnd'] = createdAtEnd;
      if (status != null) data['status'] = status;

      final response = await _baseService.post<Map<String, dynamic>>(
        '/cms/storage/cloud/list',
        data: data,
      );

      if (response.data != null) {
        final responseData = response.data!;
        if (responseData['code'] == 0 && responseData['success'] == true) {
          return responseData;
        } else {
          throw Exception(responseData['msg'] ?? '获取订单列表失败');
        }
      } else {
        throw Exception('获取订单列表响应数据为空');
      }
    } on DioException catch (e) {
      print('获取订单列表网络错误: ${e.message}');
      throw Exception('网络环境不佳，请稍后尝试');
    } catch (e) {
      print('获取订单列表错误: $e');
      throw Exception('网络环境不佳，请稍后尝试');
    }
  }

  /// 编辑用户信息
  Future<Map<String, dynamic>> editUserInfo({
    String? username,
    String? picUrl,
  }) async {
    try {
      final data = <String, dynamic>{};

      // 添加可选参数
      if (username != null) data['username'] = username;
      if (picUrl != null) data['picUrl'] = picUrl;

      final response = await _baseService.post<Map<String, dynamic>>(
        '/user/editUserInfo',
        data: data,
      );

      if (response.data != null) {
        final responseData = response.data!;
        if (responseData['code'] == 0 && responseData['success'] == true) {
          return responseData;
        } else {
          throw Exception(responseData['msg'] ?? '编辑用户信息失败');
        }
      } else {
        throw Exception('编辑用户信息响应数据为空');
      }
    } on DioException catch (e) {
      print('编辑用户信息网络错误: ${e.message}');
      throw Exception('网络环境不佳，请稍后尝试');
    } catch (e) {
      print('编辑用户信息错误: $e');
      throw Exception('网络环境不佳，请稍后尝试');
    }
  }

  /// 修改密码
  Future<Map<String, dynamic>?> modifyPassword({
    required String originPassword,
    required String newPassword,
  }) async {
    try {
      // RSA加密原始密码和新密码
      final encryptedOriginPassword = RSAUtils.encryptPassword(originPassword);
      final encryptedNewPassword = RSAUtils.encryptPassword(newPassword);

      final response = await _baseService.post<Map<String, dynamic>>(
        '/user/modifyPassword',
        data: {
          'originPassword': encryptedOriginPassword,
          'newPassword': encryptedNewPassword,
        },
      );

      if (response.data != null) {
        final responseData = response.data!;
        if (responseData['code'] == 0 && responseData['success'] == true) {
          return responseData;
        } else {
          BotToast.showText(text: responseData['msg'] ?? '修改密码失败');
          return null;
        }
      } else {
        throw Exception('修改密码响应数据为空');
      }
    } on DioException catch (e) {
      print('修改密码网络错误: ${e.message}');
      throw Exception('网络环境不佳，请稍后尝试');
    } catch (e) {
      print('修改密码错误: $e');
      throw Exception('网络环境不佳，请稍后尝试');
    }
  }
}
